using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    public float speed = 10f;
    public int damageToEnemy = 50;

    private GameObject _target;


    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
       if(_target == null)
        {
            return;
        }

        Vector3 dir = _target.transform.position - transform.position;
        float distance = speed * Time.deltaTime;
        if(dir.magnitude < distance)
        {
            HitTarget();
            return;
        }

        transform.Translate(dir.normalized * distance, Space.World);
        transform.LookAt(_target.transform);
    }

    public void Seek(GameObject target)
    {
        _target = target;
        Enemy enemy = _target.GetComponent<Enemy>();
        if(enemy)
        {
            enemy.OnDie += delegate (GameObject curtarget)
            {
                if (curtarget != null && curtarget == _target)
                {
                    Debug.Log("On Sub Event Seek");
                    _target = null;
                    Destroy(gameObject);
                }
            };
        }
    }

    void HitTarget()
    {
       if(_target != null)
        {
            Enemy e = _target.GetComponent<Enemy>();
            if(e)
            {
                e.TakeDamage(damageToEnemy);
            }
        }
    }
}
